#include					"Processor.h"
#include					"BoostAsyncTcpSocket.h"
#include					"ConnectionManager.h"
#include					<iostream>
#include					"Operator.h"

ConnectionManager::ConnectionManager(Processor &proc, boost::asio::io_service &io_service, unsigned short port) : _acceptor(io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port)), _proc(proc), _current_id(0)
{

}

ConnectionManager::~ConnectionManager()
{

}

std::string					ConnectionManager::getIp(unsigned int ip)
{
	if (_client.find(ip) != _client.end())
		return _client[ip]->getIp();
	return std::string();
}

void						ConnectionManager::SendOrderToId(IOrder *order, unsigned int id)
{
	if (_client.find(id) != _client.end())
	{
		_client[id]->sendOrder(order);
		std::cout << "sent msg to " << id << std::endl;
	}
	else
		std::cout << "no matching client to send the message id = " << id << std::endl;
}

void						ConnectionManager::start()
{
	_start_accept();
}

void						ConnectionManager::_start_accept()
{
	BoostAsyncTcpSocket		*socket;

	socket = new BoostAsyncTcpSocket(_proc, _acceptor.get_io_service(), _current_id);
	_acceptor.async_accept(socket->getSocket(), boost::bind(&ConnectionManager::_handle_accept, this, socket, boost::asio::placeholders::error));
}

void						ConnectionManager::_handle_accept(IAsyncTcpSocket *socket, const boost::system::error_code &error)
{
	if (!error)
	{
		std::cout << "new client of id " << _current_id << std::endl;
		socket->init();
		IOrder				*order = new Order;
		Protocol			proto = SERVER;
		Operator			op = WELCOME;

		order->init();
		order->pushData(&proto, sizeof(proto));
		order->pushData(&op, sizeof(op));
		socket->sendOrder(order);
		// socket->write(); [4] [SERVER] [WELCOME] [TIMESTAMP]
		// TIMESTAMP = time in millisecond (minuts * 60000 + seconds * 1000 + milliseconds)
		_client[_current_id] = socket;
		_current_id++;
	}
	else
		delete socket;
	_start_accept();
}